<?php
namespace Destroyer;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Route;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Response
{

	public static function success()
	{
        return function($data, string $message='success', int $code=0) {
            return response()->json([
                'code' => $code,
                '_as_name' => getRouteNameFromRouteObject(Route::current()),
                'message' => $message,
                'data' => $data
            ]);
        };
	}

    public static function error()
    {
        return function($request, \Throwable $e) {
            if ($e instanceof ValidationException) {
                $code = 422;
                $message = $e->getMessage();
                $errors  = $e->errors();
                $data = null;

            }elseif ($e instanceof NotFoundHttpException) {
                $code = 404;
                $message = $e->getMessage();
                $data = null;

            }elseif ($e instanceof ModelNotFoundException) {
                // 特殊404
                $code = 404;
                $message = $e->getMessage();
                $data = null;

            } elseif ($e instanceof HttpException) {
                $code = $e->getStatusCode();
                $message = $e->getMessage();
                $data = null;

            } else {
                $code = 500;
                $message = $e->getMessage();
                $data = [
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                ];
            }

            return response()->json([
                'code' => $code,
                'message' => $message,
                'errors' => $errors ?? '',
                'data' => $data
            ]);
        };
    }


}
